$(function () {
  // 特色产品内容
  function getSpecial (specialList) {
    let _html = ``;
    specialList.forEach((item, index) => {
      _html += `
      <div class="swiper-slide" data-index="${index}">
        <img src="${item.img}" alt="">
        <div class="special-list-info">
          <h4>${item.title}</h4>
          <p>${item.dist}</p>
          <p>${item.format}</p>
        </div>
        <div class="special-btn">
          <button class="left-bt">Add to bag</button>
          <button class="right-bt">Inquiry</button>
        </div>
      </div>`;
    });

    $('#special-testimonials-swiper-child').html(_html);

    // 初始化 Swiper，只初始化一次
    new Swiper('.special-products-content .swiper', {
      loop: true,
      lazyLoadingInPrevNextAmount: 1,
      lazyLoadingOnTransitionStart: true,
      navigation: {
        nextEl: ".my-swiper-button-next",
        prevEl: ".my-swiper-button-prev",
      },
      autoplay: {
        delay: 5000,
        disableOnInteraction: false,
      },
    });

    // 绑定按钮事件（事件委托，保证动态生成元素可用）
    $('#special-testimonials-swiper-child').on('click', '.left-bt', function () {
      const index = $(this).closest('.swiper-slide').index();
      const currentItem = specialList[index];
      const getInquiryList = LocalStore.get("inquiryList")
      if (!getInquiryList) {
        LocalStore.set("inquiryList", [currentItem])
      } else {
        LocalStore.update("inquiryList", list => {
          const isExist = list.some(item => item.id === currentItem.id)
          if (isExist) {
            return list.map(item => item.id === currentItem.id ? currentItem : item)
          } else {
            list.push(currentItem)
            return list
          }
        })
      }
    });

    $('#special-testimonials-swiper-child').on('click', '.right-bt', function () {
      const index = $(this).closest('.swiper-slide').index();
      const currentItem = specialList[index];
      console.log(currentItem);
    });
  }

  let interestSwiper = null;

  function initInterestSwiper () {
    let swiperOptions = {
      loop: false,
      centeredSlides: false,
      spaceBetween: (window.innerWidth <= 1025 ? 20 : 27),
      slidesPerGroup: (window.innerWidth <= 1025 ? 2 : 3),
      pagination: {
        el: '.swiper-pagination',
        clickable: true,
        dynamicBullets: false,
      },
      autoplay: {
        delay: 5000,
        disableOnInteraction: true,
      },
      simulateTouch: true,
      grabCursor: true,
      touchRatio: 1,
    };

    if (window.innerWidth <= 1025) {
      swiperOptions.slidesPerView = 2;
      swiperOptions.grid = {
        rows: 2,
        fill: "row",
      };
    } else {
      swiperOptions.slidesPerView = 3;
      swiperOptions.slidesPerGroup = 3;
      swiperOptions.loop = true;
    }

    interestSwiper = new Swiper('.dm-interested-content .swiper', swiperOptions);
  }

  // 感兴趣内容
  function getInterest (interestedList) {
    let _html = ``;
    interestedList.forEach((item) => {
      _html += `
      <div class="swiper-slide">
        <img src="${item.img}" alt="${item.title}">
        <div class="swiper-content-info">
          <h5>${item.title}</h5>
          <button class="read-more">Read more</button>
          <div class="swiper-time">
            <div class="swiper-time-info">
              <span>${item.time}</span>
            </div>
            <div class="swiper-time-info">

<svg width="16" height="12" viewBox="0 0 16 12" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7.99817 1.16406C10.1317 1.16406 11.8419 2.38438 13.0499 3.67285C13.6494 4.31225 14.1108 4.95363 14.422 5.43555C14.5712 5.66662 14.6852 5.85985 14.7628 5.99707C14.6852 6.13433 14.5714 6.3282 14.422 6.55957C14.1108 7.04147 13.6493 7.68295 13.0499 8.32227C11.842 9.61067 10.1316 10.8311 7.99817 10.8311C5.86474 10.8309 4.15434 9.61072 2.94641 8.32227C2.34698 7.68287 1.88558 7.04149 1.57434 6.55957C1.42485 6.32809 1.31109 6.13432 1.23352 5.99707C1.31106 5.85989 1.4251 5.66665 1.57434 5.43555C1.88555 4.95367 2.34705 4.31219 2.94641 3.67285C4.15434 2.38439 5.86474 1.16419 7.99817 1.16406Z" stroke="#B0B0B0" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

              <span>${item.viewNum}</span>
            </div>
          </div>
        </div>
      </div>`;
    });

    $('#testimonials-swiper-child').html(_html);

    // 每次重新生成时销毁旧的 swiper
    if (interestSwiper) {
      interestSwiper.destroy(true, true);
      interestSwiper = null;
    }
    initInterestSwiper();
  }

  // resize 自动切换 PC / Mobile
  let resizeTimer = null;
  window.addEventListener("resize", () => {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(() => {
      if (interestSwiper) {
        interestSwiper.destroy(true, true);
        interestSwiper = null;
      }
      initInterestSwiper();
    }, 300);
  });

  // 渲染感兴趣内容
  function renderInterested () {
    const bannerList = [{
      img: '../../img/PC/interested-pg.png',
      title: 'CB4512 Monocrystalline Synthetic Diamond',
      time: "Oct 18 , 2024",
      viewNum: '4.5k'
    }, {
      img: '../../img/PC/interested-pg.png',
      title: 'CB4512 Monocrystalline Synthetic Diamond',
      time: "Oct 18 , 2024",
      viewNum: '4.5k'
    }, {
      img: '../../img/PC/interested-pg.png',
      title: 'CB4512 Monocrystalline Synthetic Diamond',
      time: "Oct 18 , 2024",
      viewNum: '4.5k'
    }, {
      img: '../../img/PC/diamond.png',
      title: 'CB4512 Monocrystalline Synthetic Diamond',
      time: "Oct 18 , 2024",
      viewNum: '4.5k'
    }, {
      img: '../../img/PC/diamond.png',
      title: 'CB4512 Monocrystalline Synthetic Diamond',
      time: "Oct 18 , 2024",
      viewNum: '4.5k'
    }
    ]
    getInterest(bannerList)
  }

  // 渲染特色产品轮播
  function renderSpecial () {
    const specialList = [{
      id: 1,
      img: '../../img/PC/diamond.png',
      title: 'CB4512 Monocrystalline Synthetic Diamond',
      dist: 'Ideal Cut, DColor, VVS2 Clarity',
      format: "12715127A",
      desc: 'Ideal Cut, DColor, VVS2 Clarity',
      code: '&5127A',
      unit: 'Ct',
      sum: '239'
    }, {
      id: 2,
      img: '../../img/PC/diamond.png',
      title: 'CB4512 Monocrystalline Synthetic Diamond',
      dist: 'Ideal Cut, DColor, VVS2 Clarity',
      format: "12715127A",
      desc: 'Ideal Cut, DColor, VVS2 Clarity',
      code: '&5127A',
      unit: 'Ct',
      sum: '239'
    }
    ]
    getSpecial(specialList)
  }

  // 评论校验字段
  const leaveRules = [
    {
      key: 'comment',
      required: true,
      maxLength: 50,
      errorMessage: {
        required: 'Please enter your comment',
      }
    },
    {
      key: 'informationName',
      required: true,
      maxLength: 50,
      errorMessage: {
        required: 'Please enter your name',
        maxLength: 'The length cannot exceed 50',
      }
    },
    {
      key: 'informationEmail',
      required: true,
      maxLength: 50,
      regex: regEmail,
      errorMessage: {
        required: 'Please enter your Email',
        maxLength: 'The length cannot exceed 50',
        regex: 'Please enter a valid email'
      }
    },
  ]

  // 订阅校验字段
  const subscriptionValidationRules = [
    {
      key: 'subName',
      required: true,
      maxLength: 50,
      errorMessage: {
        required: 'Please enter your name',
        maxLength: 'The length cannot exceed 50',
      }
    },
    {
      key: 'subAccept',
      required: true,
      errorMessage: {
        required: 'Please tick the terms of consent',
      }
    },
    {
      key: 'subEmail',
      required: true,
      maxLength: 50,
      regex: regEmail,
      errorMessage: {
        required: 'Please enter your Email',
        regex: 'Please enter a valid email'
      }
    }
  ]

  // 通用校验函数
  function validateField (rule, $context) {
    const $input = $context.find(`#${rule.key}`); // 只在 $context 内查找
    const $error = $input.closest('.form-item').find('.error-message');


    // 根据类型获取值
    let value;
    if ($input.attr('type') === 'checkbox') {
      value = $input.prop('checked'); // true 或 false
    } else {
      value = $input.val().trim();
    }

    // 必填校验
    if (rule.required && !value) {
      $error.text(rule.errorMessage.required).addClass('show')
      return false
    }
    // 最大长度校验
    if (rule?.maxLength && value.length > rule.maxLength) {
      $error.text(rule.errorMessage.maxLength).addClass('show')
      return false
    }

    // 正则校验
    if (rule?.regex && value && !rule?.regex.test(value)) {
      $error.text(rule.errorMessage.regex).addClass('show')
      return false
    }

    // 校验通过
    $error.removeClass('show')
    return true
  }
  function getFormValues (leaveRulesData, $context) {
    let allValid = true
    const formValues = {}
    leaveRulesData.forEach(rule => {
      const $el = $("input[name='" + rule.key + "']")
      let value = ''
      if ($el.length) {
        if ($el.attr('type') === 'hidden') {
          value = $el.val() || ''
        } else {
          value = ($el.val() || '').trim()
        }
      }
      formValues[rule.key] = value
      // 校验必填或有校验规则的字段
      if (rule.required || rule.regex) {
        if (!validateField(rule, $context)) {
          allValid = false
        }
      }
    })
    return allValid ? formValues : null
  }


  $(document).on('click', '.dm-subscription-btn', function () {
    const $btn = $(this);
    const $wrapper = $btn.closest('.dm-subscription-content'); // 只找当前按钮所在的容器
    const formValues = getFormValues(subscriptionValidationRules, $wrapper);
    if (!formValues) return;

    const _html = `
    <div class="dm-subscription-success">Success !</div>
    <p class="dm-subscription-success-dist">
      Congratulations, you have successfully subscribed!
    </p>
  `;
    $wrapper.html(_html);
  });

  // 留下回复提交事件
  $('#handleSubmitLeave').click(function () {
    const $btn = $(this);
    const $wrapper = $btn.closest('.dm-leave'); // 只找当前按钮所在的容器
    const formValues = getFormValues(leaveRules, $wrapper)
    if (!formValues) return
    console.log('留下回复提交事件')
  })

  // 提交订阅
  // $('.dm-subscription-btn').click(function () {
  //   let _html = ''
  //   _html += ` <div class="dm-subscription-success">Success ! You're now subscribed</div>
  //         <p class="dm-subscription-success-dist">You've been successfully subscribed! Check your inbox soon for great
  //           emails from this sender.
  //         </p>`
  //   const formValues = getFormValues(subscriptionValidationRules)
  //   if (!formValues) return
  //   $('.dm-subscription-content').html(_html)
  // })


  // 侧边栏展开收起
  $(document).on("click", ".blog-point-content .point-marking svg", function () {
    const $svg = $(this);
    const $container = $svg.closest(".blog-point-content");
    const $ol = $container.find(".contents-ol");
    const $placeholder = $container.find(".point-placeholder");

    if ($ol.css("display") === "none") {
      $ol.css("display", "flex");                   // 展开 ol
      $svg.css({ transform: "rotate(90deg)", transition: "transform 0.3s" }); // 旋转箭头
      $placeholder.css("display", "none");          // 隐藏 placeholder
    } else {
      $ol.css("display", "none");                   // 收起 ol
      $svg.css({ transform: "rotate(0deg)", transition: "transform 0.3s" });  // 恢复箭头
      $placeholder.css("display", "block");         // 显示 placeholder
    }
  })

  var blogsInfoData = ["Introduction", "Diamond Shapes", "Applications", "Our Story", "Blog Tips", "Lab Diamonds", "Cut Guide", "Color Guide"];

  // 模拟数据
  const $ol = $(".contents-ol");
  // 获取所有的bolds
  function renderList (list) {
    $ol.empty();
    list.forEach(item => {
      $ol.append(`<li><a href="#">${item}</a></li>`);
    });
  }
  renderList(blogsInfoData);
  // 搜索博客......
  $("#searchBold").on("input", debounce(function () {
    const $svg = $(".point-marking svg");
    const $placeholder = $(".point-placeholder");
    const keyword = $(this).val().trim().toLowerCase();
    // 如果 ol 是收起状态，展开
    if ($ol.css("display") == "none") {
      $ol.css("display", "flex");
      $svg.css({ transform: "rotate(90deg)", transition: "transform 0.3s" });
      $placeholder.css("display", "none");          // 隐藏 placeholder

    }

    if (keyword === "") {
      renderList(blogsInfoData); // 没有输入，显示全部
    } else {
      const filtered = blogsInfoData.filter(item => item.toLowerCase().includes(keyword));
      if (filtered.length === 0) {
        renderList(blogsInfoData); // 没有匹配，显示全部
      } else {
        renderList(filtered); // 显示匹配项
      }
    }
  }))

  function init () {
    renderInterested();
    renderSpecial();
  }

  init()
})